
#include "PreHeader.h"
#include "cGameLayer.h"

#include "cGameHUDLayer.h"
#include "cMsgManager.h"
#include "cLogicManager.h"

cGameLayer::cGameLayer()
{
	m_HUDLayer = NULL;
		 
	m_logicManager = NULL;

	m_shootStart = false;
	m_moveStart = false;
}

cGameLayer::~cGameLayer()
{
	CC_SAFE_DELETE(m_logicManager);
}

bool cGameLayer::init()
{
	// setting layer
	setIsTouchEnabled(true);
	scheduleUpdate();

	srand(tUInt(time(NULL)));

	m_HUDLayer = cGameHUDLayer::node();
	addChild(m_HUDLayer, 2);

	// init logic manager
	sLogicManagerDesc desc;
	desc.parent = this;
	m_logicManager = new cLogicManager;
	
	// register msg target
	cMsgManager::it()->RegisterTarget(m_HUDLayer);
	cMsgManager::it()->RegisterTarget(m_logicManager);

	// because msg
	m_logicManager->Init(desc);
			
	return true;
}

void cGameLayer::update(ccTime dt)
{
	cMsgManager::it()->Update(dt);
	m_logicManager->Update(dt);
}

void cGameLayer::ccTouchesBegan(CCSet *touches, CCEvent *event)
{
	CCLayer::ccTouchesBegan(touches, event);

	for (CCSetIterator it = touches->begin(); it != touches->end(); it++) 
	{
		CCTouch* touch = (CCTouch*)(*it);
		if(touch == NULL)
		{
			break;
		}

		CCPoint location = touch->locationInView(touch->view());
		location = CCDirector::sharedDirector()->convertToGL(location);

		//if (location.x <= 150.0f)
		//{
			m_shootStart = true;
		//}
		
		break;
	}
}

void cGameLayer::ccTouchesMoved(CCSet *touches, CCEvent *event)
{
	CCLayer::ccTouchesMoved(touches, event);

	if (m_shootStart == true)
	{
		for (CCSetIterator it = touches->begin(); it != touches->end(); it++) 
		{
			CCTouch* touch = (CCTouch*)(*it);
			if(touch == NULL)
			{
				break;
			}

			CCPoint location = touch->locationInView(touch->view());
			location = CCDirector::sharedDirector()->convertToGL(location);

			break;
		}

		m_moveStart = true;
	}
}

void cGameLayer::ccTouchesEnded(CCSet *touches, CCEvent *event)
{
	CCLayer::ccTouchesEnded(touches, event);

	if (m_shootStart == true && m_moveStart == true)
	{
		for (CCSetIterator it = touches->begin(); it != touches->end(); it++) 
		{
			CCTouch* touch = (CCTouch*)(*it);
			if(touch == NULL)
			{
				break;
			}

			CCPoint location = touch->locationInView(touch->view());
			location = CCDirector::sharedDirector()->convertToGL(location);

			m_logicManager->Shoot(location);

			break;
		}
	}

	m_shootStart = false;
	m_moveStart = false;
}

//void cGameLayer::ccTouchesCancelled(CCSet *touches, CCEvent *event)
//{
//	CCLayer::ccTouchesCancelled(touches, event);
//}